﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Micrhard.FMCG.Server.Msg;
using Microhard.Core;
using Micrhard.FMCG.Server.Models;

namespace Micrhard.FMCG.Server.Impl
{
    public class FakeCodeImpl : IVerfFakeCode
    {
        public ExecutedResult BatchAdd(List<FakeCodeModel> model)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var emp = db.Employees.SingleOrDefault(l => l.UserName == scope.CurrentUserName);
            var now = DateTime.Now;
            foreach (var f in model)
            {
                var entity = f.ToEntity();
                entity.FakeCodeID = Guid.NewGuid();
                entity.CreateTime = now;
                entity.VerfyTime = now;
                entity.LatestTime = now;
                entity.CompanyID = emp.CompanyID;
                entity.Status = true;
                db.FakeCodes.AddObject(entity);
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, FakeCodeModelMsg.AddFailed);
                Log.Error("IVerfFakeCode.Add", ex);
            }
            return result;
        }

        public ExecutedResult Add(FakeCodeModel model)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Update(FakeCodeModel model)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var toDelete = db.FakeCodes.Where(e => ids.Contains(e.FakeCodeID)).ToList();
            toDelete.ForEach(e =>
            {
                //编码未使用，则可以删除
                if (e.Status == true)
                {
                    db.FakeCodes.DeleteObject(e);
                }
                else
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(FakeCodeModelMsg.CannotDel, e.Code));
                }
            });
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, FakeCodeModelMsg.DeleteFailed);
                    Log.Error("IVerfFakeCode.Delete", ex);
                }
            }
            return result;
        }

        public ExecutedResult Delete(FakeCodeModel model)
        {
            throw new NotImplementedException();
        }

        public FakeCodeModel GetModelByID(Guid id)
        {
            throw new NotImplementedException();
        }

        public FakeCodeModel GetModelByModel(FakeCodeModel model)
        {
            throw new NotImplementedException();
        }

        public List<FakeCodeModel> Query(FakeCodeModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var emp = db.Employees.SingleOrDefault(l => l.UserName == scope.CurrentUserName);
            IEnumerable<FakeCode> entities = from b in db.FakeCodes
                                             where b.CompanyID == emp.CompanyID
                                             select b;
            if (!string.IsNullOrEmpty(Model.SN))
            {
                entities = from b in db.FakeCodes
                           where b.CompanyID == emp.CompanyID && b.SN == Model.SN
                           select b;
            }
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.SN).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<FakeCodeModel>();
        }

        public List<FakeCodeModel> Query(FakeCodeModel Model)
        {
            throw new NotImplementedException();
        }

        public ScopeResult scope
        {
            set;
            get;
        }


        public FakeCodeModel Verify(FakeCodeModel model)
        {
            FakeCodeModel result = new FakeCodeModel();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var now = DateTime.Now;
            var entity = db.FakeCodes.SingleOrDefault(f => f.Code == model.Code);
            if (entity == null)
            {
                result.ErrorMsg = FakeCodeModelMsg.NoneCodeInfo;
                Log.Error("IVerfFakeCode.Update", "无法获取Code信息,ipAddress:" + model.IpAddress + ",VerfyTime:" + now);
                return result;
            }
            if (entity.Count == 0)
            {
                entity.VerfyTime = now;
            }
            entity.IpAddress = model.IpAddress;
            entity.Status = false;
            entity.Count = entity.Count + 1;
            entity.LatestTime = now;
            entity.Info = model.Info;
            try
            {
                db.SaveChanges();
                var newdata = db.FakeCodes.SingleOrDefault(f => f.Code == model.Code);
                result = newdata.ToModel();
            }
            catch (Exception ex)
            {
                result.ErrorMsg = EmployeeMsg.UpdateFailed;
                Log.Error("IVerfFakeCode.Update", ex);
            }
            return result;
        }
    }
}
